<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="角色管理" name="first">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
              >新增角色</el-button>
            </el-row>
            <!-- table表格 -->
            <el-table
              v-loading="tableLoading"
              class="elTable"
              :data="list"
              stripe
              style="width: 100%;"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                width="120"
              />
              <el-table-column
                prop="name"
                label="角色"
                width="240"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column label="操作">
                <template slot-scope="{ row }">
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <!-- 编辑弹层 -->
                  <el-dialog
                    :title="showTitle"
                    :visible="showDialog"
                    @close="btnCancel"
                  >
                    <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
                      <el-form-item label="角色名称" prop="name">
                        <el-input v-model.trim="roleForm.name" />
                      </el-form-item>
                      <el-form-item label="角色描述">
                        <el-input v-model="roleForm.description" />
                      </el-form-item>
                    </el-form>
                    <!-- 底部 -->
                    <el-row slot="footer" type="flex" justify="center">
                      <el-col :span="6">
                        <el-button size="small" @click="btnCancel">取消</el-button>
                        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
                      </el-col>
                    </el-row>
                  </el-dialog>
                  <el-button size="small" type="danger" @click="deleteRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="end" align="middle" style="height:60px">
              <el-pagination
                layout="prev, pager, next"
                :total="page.total"
                background
                @current-change="changePage"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="second">
            <el-row>
              <el-alert
                title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
                type="info"
                show-icon=""
                :closable="false"
              />
              <el-form label-width="120px" style="margin-top:50px">
                <el-form-item label="公司名称">
                  <el-input v-model="formData.name" disabled style="width:400px" />
                </el-form-item>
                <el-form-item label="公司地址">
                  <el-input v-model="formData.companyAddress" disabled style="width:400px" />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="formData.mailbox" disabled style="width:400px" />
                </el-form-item>
                <el-form-item label="备注">
                  <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
                </el-form-item>
              </el-form>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!--TAG 分配权限弹窗 -->
      <el-dialog title="分配权限" :visible.sync="showPermDialog">
        <!-- 树形结构 -->
        <el-tree
          ref="permTree"
          v-loading="permTreeListLoading"
          :data="permData"
          show-checkbox
          default-expand-all
          node-key="id"
          highlight-current
          :default-checked-keys="selectCheck"
          :props="defaultProps"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="showPermDialog = false">取 消</el-button>
          <el-button type="primary" @click="btnPermOk">确 定</el-button>
          <el-button @click="resetChecked">清空</el-button>
          <el-button @click="setCheckedAllKeys">全选</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getCompanyInfo, getRoleList, deleteRole, getRoleDetail, updateRole, addRole, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { mapGetters } from 'vuex'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Setting',
  components: {},
  props: {},
  data () {
    return {
      activeName: 'first',
      list: [], // 承接数组
      page: {
        page: 1, // 页码
        pagesize: 10, // 每页显示的条数
        total: 0// 记录总数
      },
      formData: {},
      tableLoading: false, // 角色管理的table
      showDialog: false,
      // 编辑弹层的表单数据
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{
          required: true,
          message: '角色名不能为空',
          trigger: 'blur'
        }]
      },
      showPermDialog: false, // 分配权限的窗口状态
      defaultProps: {
        label: 'name'
      },
      permData: [],
      selectCheck: [], // 默认选中的节点
      permTreeListLoading: false,
      roleId: ''// 当前角色id

    }
  },
  computed: {
    ...mapGetters(['companyId']),
    showTitle: {
      get () {
        return this.roleForm.id ? '编辑角色' : '新增角色'
      }
    }
  },
  watch: {},
  created () {
    // 获取角色列表
    this.getRoleList()
    // 根据id获取公司信息
    this.getCompanyInfo()
  },
  mounted () {},
  methods: {
    handleClick (tab, event) {
      // console.log(tab, event)
    },
    // TAG 获取角色管理table数据
    async getRoleList () {
      this.tableLoading = true
      const { rows, total } = await getRoleList(this.page)
      this.tableLoading = false
      this.list = rows
      this.page.total = total
    },
    // TAG 切换页码
    changePage (newPage) {
      this.page.page = newPage
      this.getRoleList()
    },
    // TAG 获取公司的信息
    async getCompanyInfo () {
      this.formData = await getCompanyInfo(this.companyId)
    },
    // TAG 删除角色
    async deleteRole (id) {
      try {
        await this.$confirm('确认删除该角色吗', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteRole(id)
        // 重新加载数据
        this.getRoleList()
        this.$message.success('删除角色成功')
      } catch (err) {
        console.log(err)
      }
    },
    async editRole (id) {
      // TAG编辑
      this.roleForm = await getRoleDetail(id)
      this.showDialog = true
    },
    // TAG 编辑取消
    btnCancel () {
      this.showDialog = false
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // TAG 编辑确定
    async  btnOK () {
      try {
        await this.$refs.roleForm.validate()
        // TODO 校验通过
        // 有id就是编辑没有则是新增
        if (this.roleForm.id) {
          // 编辑
          await updateRole(this.roleForm)
        } else {
          // 新增
          await addRole(this.roleForm)
        }
        // 重新拉去数据
        this.getRoleList()
        this.$message.success('操作成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('操作失败，请稍后重试')
      }
    },
    // TAG 分配权限确定 给角色分配权限
    async  btnPermOk () {
      // console.log(this.$refs.permTree.getCheckedKeys()) 获取当前选中的 node-key (id)
      await assignPerm({ permIds: this.$refs.permTree.getCheckedKeys(), id: this.roleId })
      this.$message.success('分配权限成功')
      this.showPermDialog = false
    },
    // TAG 点击取消
    btnPermCancel() {
      this.selectCheck = [] // 重置数据
      this.showPermDialog = false
    },
    // TAG 点击分配权限
    async assignPerm (id) {
      this.showPermDialog = true
      this.permTreeListLoading = true
      this.roleId = id // 当前点击的角色id
      // 获取所有权限点
      const data = await getPermissionList()
      this.permData = tranListToTreeData(data, '0')
      const { permIds } = await getRoleDetail(id)
      this.selectCheck = permIds // 将当前角色所拥有的权限id赋值
      this.permTreeListLoading = false
    },
    // 清空所有选中
    resetChecked () {
      this.$refs.permTree.setCheckedKeys([])
    },
    // 全选
    setCheckedAllKeys () {
      // 遍历所有id
      const keys = this.permData.map(item => {
        return item.id
      })
      this.$refs.permTree.setCheckedKeys(keys)
    }
  }
}
</script>

<style scoped lang="scss">
  ::v-deep .el-table th>.cell{
    text-align: center;
  }
  ::v-deep .el-table--enable-row-transition .el-table__body td{
      text-align: center;
    }
    ::v-deep .el-dialog {
      box-shadow: 0 1px 1px rgb(0 0 0 / 10%);
    }
</style>
